<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org" layout:decorator="layouts/simpleLayout">
<head>
    <meta charset="UTF-8">
    <title th:text="${'Add new sub category of ' + category.name}">Add new category</title>


</head>
<body>
    <div layout:fragment="bodyContent">
        <form method="post" action="/category/createNew">
            <div class="form-group">
                <label for="newCategoryName">new category name:</label>
                <input type="text" class="form-control" name="name" id="newCategoryName"/>
                <input type="hidden" th:value="${category.id}" name="parentId"/>
            </div>
            <div class="form-group">
                <label for="newCategoryShortcut">new category newCategoryShortcut:</label>
                <input type="text" class="form-control" name="shortcut" id="newCategoryShortcut"/>
            </div>
            <div class="form-group">
                <input type="button" th:attr="onclick='addNewCategory(\''+${category.id}+'\')'" class="btn btn-success" value="create"/>
            </div>

        </form>

        <script>
            function addNewCategory(pid){
                var name = $("#newCategoryName").val();
                var shortcut = $("#newCategoryShortcut").val();

                if(name === ""){
                    alert("name can not be empty.");
                    return false;
                }
				
				var checkUrl = '/category/' + name + '/check';
				$.get(checkUrl,function(e){
					if(!e){
					    doCreate(name,shortcut,pid);
					}
				}).fail(function(er){
				    alert("Server error.");
					console.log(JSON.stringify(er));
				});
                
            }
			
			function doCreate(name,shortcut,parentId){
				$.ajax({
					url:'/category/createNew',
					type:'post',
					dataType:'json',
					data:{'name':name,'shortcut':shortcut,'parentId':parentId},
					success:function(data){
						if(data.success){
						    alert("Add success.");
						    window.location.reload();
						}
					},
					error:function(er){
						alert("Add new category fail");
						console.log(JSON.stringify(er));
					}
				});
			}
        </script>
    </div>

</body>
</html>